<template>
  <div class="login">

    <div class="container">
      <div class="w">
        <div class="user-box">
          <div class="tabs-top">
            <span class="tab1">{{((key)=>{
                switch(key){
                  case false: return '登 录';break;
                  case true: return '修改密码';break;
                }
              })(isActive)}}</span>
          </div>
          <!-- 手机号登录 -->
          <div class="tabs-con" v-show="!isActive">
            <el-form :model="userInfo" status-icon ref="userInfo" :rules="rules">
              <div class="email-phone">
                <el-form-item prop="phone">
                  <el-input prefix-icon="el-icon-user" placeholder="请输入手机号" v-model="userInfo.phone" autocomplete="off">
                  </el-input>
                </el-form-item>
              </div>

              <div class="password-code">
                <el-form-item prop="password">
                  <el-input prefix-icon="el-icon-lock" placeholder="请输入密码" v-model="userInfo.password" show-password autocomplete="off">
                  </el-input>
                </el-form-item>
              </div>

              <!-- 滑块验证 -->
              <Slider></Slider>
              <!-- 滑块验证-end -->

              <el-button class="btn" type="primary" @click="submit('userInfo')">立即登录</el-button>
              <div class="links">
                <el-link type="primary" @click="forgot(true)">忘记密码？</el-link>
                <el-link type="primary" class="fr" @click="goPage('Register')">没有账号，点击注册</el-link>
              </div>
            </el-form>
          </div>
          <!-- 忘记密码 -->
          <div class="tabs-con" v-show="isActive">
            <el-form :model="userInfo" status-icon ref="userInfo2" :rules="rules2">
              <div class="email-phone">
                <el-form-item prop="email">
                  <el-input class="email_inner" prefix-icon="el-icon-message" placeholder="请输入邮箱" v-model="userInfo.email" @change="checkEmpty">
                  </el-input>
                  <el-button type="primary" size="small" class="btn-code" @click="sendCode" :disabled="isSend">{{text}}</el-button>
                </el-form-item>
              </div>

              <div class="password-code">
                <el-form-item prop="validcode">
                  <el-input prefix-icon="el-icon-key" placeholder="请输入验证码" v-model="userInfo.validcode" @change="checkEmpty">
                  </el-input>
                </el-form-item>
              </div>

              <el-button class="btn" type="primary" :disabled="isAble" @click="checkEmail">修改密码</el-button>
              <div class="links">
                <el-link type="primary" @click="forgot(false)">密码登录</el-link>
                <el-link type="primary" class="fr" @click="goPage('Register')">没有邮箱，点击注册</el-link>
              </div>
            </el-form>
          </div>
        </div>
      </div>
    </div>

    <!-- 修改密码 -->
    <el-dialog title="修改密码" :visible.sync="changePw" width="300px" center>
      <el-form :model="changeForm" status-icon ref="changeForm" :rules="rules3" label-width="80px">
        <el-form-item prop="n_pw" label="新密码">
          <el-input placeholder="新密码" v-model="changeForm.n_pw">
          </el-input>
        </el-form-item>

        <el-form-item prop="a_pw" label="确认密码">
          <el-input placeholder="确认密码" v-model="changeForm.a_pw">
          </el-input>
        </el-form-item>

      </el-form>
      <div class="btns">
        <el-button @click="changePw = false">取 消</el-button>
        <el-button type="primary" @click="setNewPw">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import Slider from "@/components/Slider";
import "@/assets/less/login.less";
export default {
  name: "Login",

  components: {
    Slider,
  },

  data() {
    return {
      isLogin: false,
      // 用户信息
      userInfo: {
        phone: "",
        password: "",
        email: "",
        validcode: "",
      },

      // 是否忘记密码
      isActive: false,

      // 判断表单是否为空
      isAble: true,

      // 修改密码
      changePw: false,
      //验证表单规则
      rules: {
        phone: [{ validator: this.validPhone, trigger: "blur" }],
        password: [{ validator: this.validPassword, trigger: "blur" }],

      },

      // 邮箱和验证码验证格式
      rules2: {
        email: [{ validator: this.validEmail, trigger: "blur" }],
        validcode: [{ validator: this.validCode, trigger: "blur" }],
      },

      // 修改密码表单
      changeForm: {
        o_pw: '',
        n_pw: '',
        a_pw: ''
      },
      rules3: {
        n_pw: [{ validator: this.validPassword, trigger: "blur" }],
        a_pw: [{ validator: this.validApw, trigger: "blur" }],
      },
      // 验证码id
      codeId: '',
      text: '获取验证码',
      isSend: false,
    };
  },

  created() {
    let isLogin = false;
    if (this.$cookies.get('__tk')) {
      isLogin = true;
      this.$router.push('/home')
    } else {
      isLogin = false;
    }
    console.log('Home isLogin==>', isLogin)
    let oj = {
      title: '落新家',
      nav: 'Login',
      isLogin: isLogin,
    };
    this.$emit('isTitle', oj);
  },

  methods: {
    // 跳转页面
    goPage(n) {
      this.$router.push({ name: n });
    },
    // 切换选项卡
    forgot(bool) {
      if (this.isActive == bool) {
        return;
      }
      this.isActive = bool;
    },
    // 发起登录请求
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          // return this.$message.warning("请输入手机号或密码");
          return
        }

        if (!this.$store.state.isSuccess) {
          this.$message.warning("请验证滑块!");
          return;
        }
        console.log("发起登录请求");

        // 发起登录请求
        this.axios({
          method: 'POST',
          url: this.baseUrl + '/login',
          data: {
            phone: this.userInfo.phone,
            password: this.userInfo.password
          }
        }).then(res => {
          console.log('res ==> ', res);
          if (res.data.code == 1030) {
            this.$message({
              message: `${res.data.msg}！即将前往首页。`,
              type: 'success'
            });
            // 将token保存在cookie中
            // for (let key in res.data.data) {
            //   this.$cookies.set(key, res.data.data[key], '1d');
            // }
            this.$cookies.set('__tk', res.data.data.token, '1d');
            this.$cookies.set('__ui', res.data.data.userId, '1d');
            this.$cookies.set('__un', res.data.data.userName, '1d');

            // 跳转后台首页
            setTimeout(() => {
              this.$router.push({ name: 'Home' })
            }, 1000);
          } else {
            this.$message({
              message: res.data.msg,
              type: 'error'
            });
          }
        }).catch(err => {
          console.log('err ==> ', err);

        });
      });
    },
    // 发起验证邮箱请求
    checkEmail() {
      this.$refs['userInfo2'].validate((valid) => {
        if (!valid) {
          return
        }
        this.axios({
          method: 'post',
          url: this.baseUrl + '/checkEmail',
          data: {
            email: this.userInfo.email,
            // 验证码
            validcode: this.userInfo.validcode,
            // 验证码id
            codeId: this.codeId
          }
        }).then(res => {
          console.log('res==>', res)
          if (res.data.code == 200) {
            this.changePw = true;

          } else {
            this.$message.error(res.data.msg)
          }
        }).catch(err => {
          console.log('err==>', err)
          this.$message.error(res.data.msg)
        })
      });

    },
    // 修改密码
    setNewPw() {
      // 验证新密码
      this.$refs['changeForm'].validate((valid) => {
        if (!valid) {
          return
        }
        this.axios({
          method: 'post',
          url: this.baseUrl + '/changePw',
          data: {
            email: this.userInfo.email,
            password: this.changeForm.a_pw
          }
        }).then(res => {
          console.log('res==>', res)
          if (res.data.code == 200) {
            this.$message.success(res.data.msg)
            this.changePw = false;
            this.isActive = false;
          } else {
            this.$message.error(res.data.msg)
          }
        }).catch(err => {
          console.log('err==>', err)
          this.$message.error(res.data.msg)
        })
      });
    },
    //验证邮箱
    validEmail(rule, value, callback) {
      if (!value) {
        return callback(new Error("请输入邮箱"));
      }
      setTimeout(() => {
        let reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
        if (!reg.test(value)) {
          callback(new Error("邮箱格式不正确"));
        } else {
          callback();
        }
      }, 400);
    },

    //验证密码(首字符为字母, 字母数字_组合, 6-16位)
    validPassword(rule, value, callback) {
      if (!value) {
        callback(new Error("请输入密码"));
      }
      setTimeout(() => {
        // let reg = /^[A-Za-z]\w{5,15}$/;
        // if (!reg.test(value)) {
        //   callback(new Error("密码必须以字母开头，可包含字母数字_"));
        // } else {
        //   callback();
        // }
        callback();
      }, 400);
    },

    // 手机号验证
    validPhone(rule, value, callback) {
      if (value == "") {
        return callback(new Error("请输入手机号"));
      }
      setTimeout(() => {
        let reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
        if (!reg.test(value)) {
          callback(new Error("手机格式错误"));
        } else {
          callback();
        }
      }, 400);
    },

    //验证验证码
    validCode(rule, value, callback) {
      if (!value) {
        return callback(new Error("验证码不能为空"));
      }
      setTimeout(() => {
        let reg = /^\d{6}$/;
        if (!reg.test(value)) {
          callback(new Error("验证码必须为6位数字"));
        } else {
          callback();
        }
      }, 400);
    },

    // 验证确认密码
    validApw(rule, value, callback) {
      if (value == '') {
        callback(new Error("请输入密码"));
      } else if (value != this.changeForm.n_pw) {
        callback(new Error('两次密码不相同'))
      }
      callback();
    },

    // 检验输入框是否为空
    checkEmpty() {
      if (this.userInfo.email == "" || this.userInfo.validcode == "") {
        this.isAble = true;
      } else {
        this.isAble = false;
      }
    },

    //获取验证码
    sendCode() {
      //验证邮箱格式是否正确
      let reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
      if (!reg.test(this.userInfo.email)) {
        this.$message.warning("请输入正确的邮箱！")
        return;
      }

      let time = 5;
      this.text = `${time}s后重新发送`;
      this.isSend = true;

      let timer = setInterval(() => {
        if (time == 0) {
          clearInterval(timer);
          timer = null;
          this.text = '获取验证码';
          this.isSend = false;

        } else {
          time--;
          this.text = `${time}s后重新发送`;
        }
      }, 1000)

      //发起获取验证码请求
      this.axios({
        method: 'POST',
        url: this.baseUrl + '/email',
        data: {
          email: this.userInfo.email
        }
      }).then(res => {
        console.log('res ==> ', res);
        if (res.data.code == 1010) {
          this.codeId = res.data.cid;
          console.log('验证码==>', res.data.Code)
          this.$message({
            message: res.data.msg,
            type: 'success'
          });
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(err => {
        this.$message.error(res.data.msg);
        console.log('err ==> ', err);
      })
    },


  },
};
</script>
